var zTree;
var roleId;
//打开model弹窗并加载树状结构菜单
function showMenuTreeModel(id){
	roleId = id;
	var setting = {
			view: {
				//addHoverDom: addHoverDom,
				//removeHoverDom: removeHoverDom,
				selectedMulti: true
			},
			check: {
				enable: true
			},
			data: {
				simpleData: {
					enable: true,
					pIdKey:'parentId'//设置父节点的名称为parentId,则会自动读取parentId值作为父节点id
				}
			},
			edit: {
				enable: false
			}
		};

	var zNodes = getMenuTree();//获取菜单信息
	
	$.fn.zTree.init($("#menuTree"), setting, zNodes).expandAll(true);//初始化并设置默认打开所有节点
	
	//设置角色对应的已有菜单权限为默认选中状态
	zTree = $.fn.zTree.getZTreeObj("menuTree");
	var roleMenu = getMenuTree(id);//读取该角色拥有的菜单信息
	if(roleMenu != null && roleMenu.length > 0){
		for(var i = 0; i < roleMenu.length; i++){
			var node = zTree.getNodeByParam("id", roleMenu[i].id);
			if(node != null)
				zTree.checkNode(node, true);
		}
	}

	$('#menuTreeModel').modal('show');//显示model弹框
}

//异步获取菜单信息
function getMenuTree(roleId){
	var menus = '';
	var url = '/admin/sys/menu/menuTree';
	if(roleId){
		url = '/admin/sys/menu/ajaxRoleMenus?roleId='+roleId;
	}
	$.ajax({
		url:url,
		type: 'post',
		dataType: 'json',
		async: false,
		success: function(obj){
			if(obj.status == 200) {
				menus = obj.data;
			}
		},
		error: function(){
			
		}
	});
	return menus;
}

//提交角色-菜单信息
$('#menuTreeModel-submit').on('click',function(){
	var checkedNodes = zTree.getCheckedNodes();
	var ids = '';
	if(checkedNodes != null || checkedNodes.length > 0){
		for(var i = 0; i < checkedNodes.length; i++){
			ids += checkedNodes[i].id + ',';
		}
		ids = ids.substring(0, ids.lastIndexOf(','));
	}
	$.ajax({
		url:'/admin/sys/role/setRoleMenusAuth',
		data: {"roleId":roleId,"menuIds":ids},
		type: 'post',
		dataType: 'json',
		async: false,
		success: function(obj){
			if(obj.status == 200) {
				gritterSuccess(obj.data);
			}
		},
		error: function(){
			//alert('请求有误');
		}
	});
	$('#close-modal').trigger('click');//关闭modal
//	$('#menuTreeModel').hide();
})

//显示权限结构树model时触发的事件
$('#menuTreeModel').on('show.bs.modal', function () {
//	alert("打开");
})
//关闭model，清空树状菜单
$('#menuTreeModel').on('hide.bs.modal', function () {
	$("#menuTree").html('');
})


jQuery(function($) {
	  
	var grid_selector = "#grid-table";//列表
	var pager_selector = "#grid-pager";//分页行
	
	var parent_column = $(grid_selector).closest('[class*="col-"]');
	//resize to fit page size
	$(window).on('resize.jqGrid', function () {
		$(grid_selector).jqGrid( 'setGridWidth', parent_column.width() );
    })
	
	//resize on sidebar collapse/expand
	$(document).on('settings.ace.jqGrid' , function(ev, event_name, collapsed) {
		if( event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed' ) {
			//setTimeout is for webkit only to give time for DOM changes and then redraw!!!
			setTimeout(function() {
				$(grid_selector).jqGrid( 'setGridWidth', parent_column.width() );
			}, 20);
		}
    })
	
	//if your grid is inside another element, for example a tab pane, you should use its parent's width:
	/**
	$(window).on('resize.jqGrid', function () {
		var parent_width = $(grid_selector).closest('.tab-pane').width();
		$(grid_selector).jqGrid( 'setGridWidth', parent_width );
	})
	//and also set width when tab pane becomes visible
	$('#myTab a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
	  if($(e.target).attr('href') == '#mygrid') {
		var parent_width = $(grid_selector).closest('.tab-pane').width();
		$(grid_selector).jqGrid( 'setGridWidth', parent_width );
	  }
	})
	*/
	
	jQuery(grid_selector).jqGrid({
//		caption: "角色列表",			
		subGrid : false,//是否开启子菜单
//		styleUI: 'Bootstrap',
		data: getMenuData(),//异步加载数据
//		url:'/admin/sys/role/ajaxRolesList',
//		datatype:"json",
		datatype: "local",
		height: '100%',
		colNames:['角色ID', '角色名称', '角色描述', '是否可用', '权限','编辑'],
		colModel:[
			
			{name:'id',index:'id', sorttype:"int", editable: true, hidden: true},
			{name:'name',index:'name', editable:true, editoptions:{size:"20",maxlength:"30"}, editrules:{required: true}},
			{name:'description',index:'description', editable: true,editoptions:{size:"20",maxlength:"30"}},
			//, formatter: formatAvailable   //unformat: aceSwitch
			{name:'available',index:'available', align:'center', editable: true,edittype:"select", width:30,
				formatter:'select', editoptions: {value:"0:是;1:否"},unformat: aceSwitch},
			{name: 'myac', index: '', align:'center', fixed: true, sortable: false, resize: false, search: false, 
	            formatter: function (value, grid, rows, state) { 
//		            	return '<button class="btn btn-xs" id="example" rel="popover" data-content="" data-placement="right" onclick="gPopover()" data-original-title="权限菜单"><i class="ace-icon fa fa-unlock-alt active"></i> 权限设置</button>'
	            	// data-target="#menuTreeModel"   
	            	return '<button class="btn btn-primary btn-xs" data-toggle="modal" onclick="showMenuTreeModel(\''+rows.id+'\')"><i class="ace-icon fa fa-unlock-alt active"></i> 权限设置</button>'; 
	            }
	        }, 
			{name:'oper',index:'', fixed:true, sortable:true, resize:true, search: false,
				formatter:'actions', 
				formatoptions:{
					keys:true,
					//delbutton: false, //disable delete button
					//,afterComplete:function(xhr){ showOperInfo(xhr);}
					delOptions:{
						recreateForm: true, 
						beforeShowForm:beforeDeleteCallback, 
						closeAfterDel: true,
						afterComplete:function(xhr){//删除之后的回调
							showOperInfo(xhr);
					    }
					},
					editformbutton:true, 
					editOptions:{
						recreateForm: true, 
						beforeShowForm:beforeEditCallback, 
						closeAfterEdit: true,
						afterComplete:function(xhr){//修改之后的回调
							showOperInfo(xhr);
					    }
					}
				}
			}
		], 
		
		viewrecords : true,
		rowNum:10,
		rowList:[10,20,30],
		pager : pager_selector,
		altRows: true,
		//toppager: true,
		
		multiselect: true,
        multiboxonly: true,
        reloadAfterSubmit: true, //成功保存记录后重新加载grid数据
		loadComplete : function(e) {//表格加载完成
			var table = this;
			setTimeout(function(){
				styleCheckbox(table);
				
				updateActionIcons(table);
				updatePagerIcons(table);
				enableTooltips(table);
			}, 0);
		},
		
		autowidth: true,
		
		//cellEdit:true
		/**
		,
		grouping:true, 
		groupingView : { 
			 groupField : ['name'],
			 groupDataSorted : true,
			 plusicon : 'fa fa-chevron-down bigger-110',
			 minusicon : 'fa fa-chevron-up bigger-110'
		},
		caption: "Grouping"
		*/
		editurl: "/admin/sys/role/operation"//下方导航栏增、删、改操作请求的路径
	});

	//enable search/filter toolbar
	//jQuery(grid_selector).jqGrid('filterToolbar',{defaultSearch:true,stringResult:true})
	//jQuery(grid_selector).filterToolbar({});

	$(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size

	//显示操作后的回调信息，并且重新刷新表格
	function showOperInfo(xhr){
		if(xhr.responseJSON){
			if(xhr.responseJSON.status == 200){
				gritterSuccess(xhr.responseJSON.data);
			}else{
				gritterError(xhr.responseJSON.data);
			}
		}else{
			gritterError(info.noAuth);
		}
        
        $(grid_selector).jqGrid('clearGridData');
        $(grid_selector).jqGrid('setGridParam', {
        	data: getMenuData(),//重新加载数据
        }).trigger('reloadGrid');
	}
	
	//异步加载数据
	function getMenuData(){
		var data = [];
		var url = '/admin/sys/role/ajaxRolesList';
		$.ajaxSettings.async = false;
		$.getJSON(url,'',function(result, e){
			if(result.error){
				
            }else{
                data = result.data;
            }
		});
		return data;
	}
	
	//将0、1转换为文字是、否
	function formatAvailable(cellValue, options, rowObject){
		if(cellValue == 0){
			return '<span class="label label-sm label-success">是</span>';
		}else{
			return '<span class="label label-sm label-danger">否</span>';
		}
	}

	//switch element when editing inline
	function aceSwitch( cellvalue, options, cell ) {
		setTimeout(function(){
			$(cell) .find('input[type=checkbox]')
				.addClass('ace ace-switch ace-switch-5')
				.after('<span class="lbl"></span>');
		}, 0);
	}
	
	
	//enable datepicker
	function pickDate( cellvalue, options, cell ) {
		setTimeout(function(){
			$(cell) .find('input[type=text]')
				.datepicker({format:'yyyy-mm-dd' , autoclose:true}); 
		}, 0);
	}

	//下方的按钮
	var gGrid = jQuery(grid_selector).jqGrid('navGrid',pager_selector,
		{ 	//navbar options
			add: true,
			addicon : 'ace-icon fa fa-plus-circle purple',
			edit: false,
			editicon : 'ace-icon fa fa-pencil blue',
			del: true,
			delicon : 'ace-icon fa fa-trash-o red',
			search: true,
			searchicon : 'ace-icon fa fa-search orange',
			refresh: false,
			refreshicon : 'ace-icon fa fa-refresh green',
			view: true,
			viewicon : 'ace-icon fa fa-search-plus grey',
//			auth: false,
//			viewicon : 'ace-icon fa fa-unlock-alt black'
		},
		{
			//编辑
			closeAfterEdit: true,
			//width: 700,
			recreateForm: true,
			beforeShowForm : function(e) {
				var form = $(e[0]);
				form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
				style_edit_form(form);
			},
			afterComplete:function(xhr){//修改之后的回调
				showOperInfo(xhr);
		    }
		},
		{
			//添加
			//width: 700,
			closeAfterAdd: true,
			recreateForm: true,
			viewPagerButtons: false,
			beforeShowForm : function(e) {
				var form = $(e[0]);
				form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
				.wrapInner('<div class="widget-header" />')
				style_edit_form(form);
			},
			afterComplete:function(xhr){//添加之后的回调
				showOperInfo(xhr);
		    }
		},
		{
			//删除
			recreateForm: true,
			beforeShowForm : function(e) {
				var form = $(e[0]);
				if(form.data('styled')) return false;
				
				form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
				style_delete_form(form);
				
				form.data('styled', true);
			},
			afterComplete:function(xhr){//删除之后的回调
				showOperInfo(xhr);
		    }
//			,
//			onClick : function(e) {
//				//alert(1);
//			}
		},
		{
			//搜索
			recreateForm: true,
			afterShowSearch: function(e){
				alert('afterShowSearch-start');
				var form = $(e[0]);
				form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
				style_search_form(form);
				alert('afterShowSearch-end');
			},
			afterRedraw: function(){
				alert('afterRedraw-start');
				style_search_filters($(this));
				alert('afterRedraw-end');
			}
			,
			multipleSearch: true,
			/**
			multipleGroup:true,
			showQuery: true
			*/
		},
		{
			//查看记录
			recreateForm: true,
			beforeShowForm: function(e){
				var form = $(e[0]);
				form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
			}
		}
	)
	
	//增加权限弹窗按钮
	/*gGrid.navButtonAdd(pager_selector, {
        caption: "",
        title:"设置权限",
        buttonicon: "ace-icon fa fa-unlock-alt green",
        position: "last",
        beforeShowForm:function(e){
        	gPopover();
        	form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
        },
        onClickButton: function (e) {  
        	var s;
            //多选获取
            s = jQuery(grid_selector).jqGrid('getGridParam', 'selarrrow');
        }
    })*/

	//编辑弹框的样式
	function style_edit_form(form) {
		//enable datepicker on "sdate" field and switches for "stock" field
		form.find('input[name=sdate]').datepicker({format:'yyyy-mm-dd' , autoclose:true})
		
		form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
				   //don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)
				  //.addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');
				
		//update buttons classes
		var buttons = form.next().find('.EditButton .fm-button');
		buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
		buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
		buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')
		
		buttons = form.next().find('.navButton a');
		buttons.find('.ui-icon').hide();
		buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
		buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');		
	}
	
	//删除弹框的样式
	function style_delete_form(form) {
		var buttons = form.next().find('.EditButton .fm-button');
		buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
		buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
		buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
	}
	
	//搜索过滤部分的样式	
	function style_search_filters(form) {
		form.find('.delete-rule').val('X');
		form.find('.add-rule').addClass('btn btn-xs btn-primary');
		form.find('.add-group').addClass('btn btn-xs btn-success');
		form.find('.delete-group').addClass('btn btn-xs btn-danger');
	}
	
	//搜索弹框的样式
	function style_search_form(form) {
		var dialog = form.closest('.ui-jqdialog');
		var buttons = dialog.find('.EditTable')
		buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
		buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
		buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
	}
	
	//删除之前
	function beforeDeleteCallback(e) {
		var form = $(e[0]);
		if(form.data('styled')) return false;
		
		form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
		style_delete_form(form);
		
		form.data('styled', true);
	}
	
	//编辑之前
	function beforeEditCallback(e, cellvalue, options) {
		console.log(options);
		var form = $(e[0]);
		form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
		style_edit_form(form);
	}


	//it causes some flicker when reloading or navigating grid
	//it may be possible to have some custom formatter to do this as the grid is being created to prevent this
	//or go back to default browser checkbox styles for the grid
	//复选框样式
	function styleCheckbox(table) {
	/**
		$(table).find('input:checkbox').addClass('ace')
		.wrap('<label />')
		.after('<span class="lbl align-top" />')

		$('.ui-jqgrid-labels th[id*="_cb"]:first-child')
		.find('input.cbox[type=checkbox]').addClass('ace')
		.wrap('<label />').after('<span class="lbl align-top" />');
	*/
	}
	

	//unlike navButtons icons, action icons in rows seem to be hard-coded
	//you can change them like this in here if you want
	function updateActionIcons(table) {
		/**
		var replacement = 
		{
			'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
			'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
			'ui-icon-disk' : 'ace-icon fa fa-check green',
			'ui-icon-cancel' : 'ace-icon fa fa-times red'
		};
		$(table).find('.ui-pg-div span.ui-icon').each(function(){
			var icon = $(this);
			var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
			if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
		})
		*/
	}
	
	//replace icons with FontAwesome icons like above
	function updatePagerIcons(table) {
		var replacement = 
		{
			'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140',
			'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140',
			'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140',
			'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'
		};
		$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
			var icon = $(this);
			var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
			
			if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
		})
	}
	
	function enableTooltips(table) {
		$('.navtable .ui-pg-button').tooltip({container:'body'});
		$(table).find('.ui-pg-div').tooltip({container:'body'});
	}

	//var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

	$(document).one('ajaxloadstart.page', function(e) {
		$.jgrid.gridDestroy(grid_selector);
		$('.ui-jqdialog').remove();
	});
});


/**************树状表格****************/


//鼠标悬停显示编辑框
var newCount = 1;
function addHoverDom(treeId, treeNode) {
	var sObj = $("#" + treeNode.tId + "_span");
	if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
	var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
		+ "' title='add node' onfocus='this.blur();'></span>";
	sObj.after(addStr);
	var btn = $("#addBtn_"+treeNode.tId);
	if (btn) btn.bind("click", function(){
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		zTree.addNodes(treeNode, {id:(100 + newCount), pId:treeNode.id, name:"new node" + (newCount++)});
		return false;
	});
};

//鼠标移除取消编辑框
function removeHoverDom(treeId, treeNode) {
	$("#addBtn_"+treeNode.tId).unbind().remove();
};
